<template>
  <div ref="page_box" style="padding-bottom:1rem;padding-top:1.5rem;background: #f5f5f5;height:100%;overflow-y: scroll;">
    <div class="header">
      <TopNav :title="curr_user" show_left="true" back_url="/#/recharge_by_kf"></TopNav>
    </div>
    <div>
      <ul class="his-list" v-if="his">
        <li v-for="(item, index) in his">
          <div :class="item.is_self?'self':'no_self'" class="msg-row">
            <template v-if="item.is_self">
              <div>
                <template v-if="item.msg_type==0">
                  {{item.content}}
                </template>
                <template v-else>
                  <img @click="handleClickReviewImg(item.content)" style="max-width: 150px;max-height: 150px;" :src="item.content" alt="">
                </template>
                <span class="time_at">{{item.is_read?'✔✔':'✔'}} {{item.when}}</span>
              </div>
              <div>
                <img src="/static/img/headphoto/1.4.jpg" alt="">
              </div>
            </template>
            <template v-else>
              <div>
                <img src="../../static/img/kf2.png" alt="">
              </div>
              <div>
                <template v-if="item.msg_type==0">
                  {{item.content}}
                </template>
                <template v-else>
                  <img @click="handleClickReviewImg(item.content)" style="max-width: 150px;max-height: 150px;" :src="item.content" alt="">
                </template>
                <span class="time_at">{{item.is_read?'✔✔':'✔'}} {{item.when}}</span>
              </div>
            </template>
          </div>
        </li>
      </ul>
<!--      <ul class="kf-list" v-if="data">-->
<!--        <li v-for="(item, index) in data">-->
<!--          <div>-->
<!--            <img src="../../static/img/kf2.png" alt="">-->
<!--          </div>-->
<!--          <div :id="'wechat_'+index" @click="copyHere('wechat_'+index)" data-clipboard-action="copy" :data-clipboard-text="item">-->
<!--            {{item}}-->
<!--          </div>-->
<!--        </li>-->
<!--      </ul>-->
    </div>
    <div style="position: fixed;bottom:0;width:100%;">
      <van-search
        v-model="text"
        show-action
        left-icon=""
        @search="onSend"
        placeholder="$t('KfPage.qsr')"
      >
        <template #action>
          <audio id="audio-tips" src="/static/sounds/msn.mp3"/>
          <div @click="onSend">{{ $t('KfPage.fs') }}</div>
        </template>
        <template slot="left">
          <input @change="handleChangeImg" accept="image/jpeg,image/png" ref="upload_img" style="display: none" type="file">
          <img @click="handleClickImg" class="tools-img" src="../../static/icons/pic.png" alt="">
          <img style="width:30px;height:30px;" class="tools-img" src="../../static/icons/smill.png" alt="">
        </template>
      </van-search>
      <van-overlay :show="showImg" @click="showImg = false">
        <div class="wrapper" style="padding-top:30%;">
          <img :src="curr_img" style="max-width:100%;max-height: 90%;" alt="">
        </div>
      </van-overlay>
    </div>
  </div>
</template>

<script>

import Vue from 'vue';
import { Search,Overlay } from 'vant';
Vue.use(Search);
Vue.use(Overlay);

import MainNav from "../components/MainNav";
import UserAccountHeader from "../components/UserAccountHeader";
import TopNav from "../components/TopNav";
import EmptyBox from "../components/EmptyBox";
import VueSocketIO from "vue-socket-io";

import 'vant/lib/search/style';
import 'vant/lib/overlay/style';
//Vue.use(VueSocketIO, "https://down2.wan77.net");

export default {
  name: 'KfPage',
    components: {EmptyBox, MainNav,UserAccountHeader,TopNav},
    data () {
    return {
        loading:false,
        user:'',
        total:0,
        showImg: false,
        curr_id: 0,
        curr_img:'',
        curr_user: '',
        his: [
            // {
            //     from_user: this.$t('KfPage.dhl'),
            //     to_user:this.$t('KfPage.xbt'),
            //     content: '你好,在吗',
            //     is_read: 1,
            //     msg_type: 0,
            //     is_self: 1,
            //     created_at: '22秒前'
            // },
            // {
            //     from_user: this.$t('KfPage.dhl'),
            //     to_user:this.$t('KfPage.xbt'),
            //     content: this.$t('KfPage.wycz'),
            //     is_read: 1,
            //     msg_type: 0,
            //     is_self: 1,
            //     created_at: '22秒前'
            // },
            // {
            //     from_user: this.$t('KfPage.dhl'),
            //     to_user:this.$t('KfPage.xbt'),
            //     content: '3000块钱',
            //     is_read: 1,
            //     msg_type: 0,
            //     is_self: 1,
            //     created_at: '22秒前'
            // },
            // {
            //     from_user: this.$t('KfPage.dhl'),
            //     to_user:this.$t('KfPage.xbt'),
            //     content: this.$t('KfPage.yhm'),
            //     is_read: 1,
            //     msg_type: 0,
            //     is_self: 1,
            //     created_at: '22秒前'
            // },
            // {
            //     from_user: this.$t('KfPage.xbt'),
            //     to_user:this.$t('KfPage.dhl'),
            //     content: this.$t('KfPage.yd'),
            //     is_read: 1,
            //     msg_type: 0,
            //     is_self: 0,
            //     created_at: '22秒前'
            // },
            // {
            //     from_user: this.$t('KfPage.dhl'),
            //     to_user:this.$t('KfPage.xbt'),
            //     content: this.$t('KfPage.kfh'),
            //     is_read: 0,
            //     msg_type: 0,
            //     is_self: 1,
            //     created_at: '22秒前'
            // },
            // {
            //     from_user: this.$t('KfPage.xbt'),
            //     to_user:this.$t('KfPage.dhl'),
            //     content: this.$t('KfPage.hdxfk'),
            //     is_read: 0,
            //     msg_type: 0,
            //     is_self: 0,
            //     created_at: '22秒前'
            // },
            // {
            //     from_user: this.$t('KfPage.dhl'),
            //     to_user:this.$t('KfPage.xbt'),
            //     content: this.$t('KfPage.yfk'),
            //     is_read: 0,
            //     msg_type: 0,
            //     is_self: 1,
            //     created_at: '22秒前'
            // },
            // {
            //     from_user: this.$t('KfPage.dhl'),
            //     to_user:this.$t('KfPage.xbt'),
            //     content: 'https://aifenxiang.obs.ap-southeast-1.myhuaweicloud.com:443/15890847078672.png',
            //     is_read: 0,
            //     msg_type: 1,
            //     is_self: 1,
            //     created_at: '22秒前'
            // },
            // {
            //     from_user: this.$t('KfPage.xbt'),
            //     to_user:this.$t('KfPage.dhl'),
            //     content: this.$t('KfPage.yfh'),
            //     is_read: 0,
            //     msg_type: 0,
            //     is_self: 0,
            //     created_at: '22秒前'
            // },
            // {
            //     from_user: this.$t('KfPage.xbt'),
            //     to_user:this.$t('KfPage.dhl'),
            //     content: 'https://aifenxiang.obs.ap-southeast-1.myhuaweicloud.com:443/15890847078672.png',
            //     is_read: 0,
            //     msg_type: 1,
            //     is_self: 0,
            //     created_at: '22秒前'
            // },
            // {
            //     from_user: this.$t('KfPage.dhl'),
            //     to_user:this.$t('KfPage.xbt'),
            //     content: 'ok',
            //     is_read: 0,
            //     msg_type: 0,
            //     is_self: 1,
            //     created_at: '22秒前'
            // }
        ],
        text: '',
        sel_img:'',
        to_type: 'daichong',
    }
  },
    methods:{
      handleClickImg(){
        this.$refs.upload_img.click();
      },
      initServer(){
          this.$socket.emit('connect');
          this.$socket.on('new_msg', (msg)=>{
              this.playAutio();
              msg = msg.replace(/&quot;/g, '"')
              console.log(msg)
              let data = JSON.parse(msg)
              if(data.code == 0){
                  this.$toast.text(msg)
              }
              if(data.from_uid == this.curr_id){
                  this.getMsg(data.msg_id);
              }
          });
      },
        handleClickReviewImg(url){
          this.curr_img = url;
          this.showImg = true;
        },
        handleChangeImg(e){
          let file = e.target.files[0];
            this.loading = true;
            let param = new FormData();
            // to_uid: this.curr_id,
            // to_user: this.curr_user,
            // content: this.text,
            // to_type: 'daichong',
            //param.append("username",this.data.username);
            param.append("to_uid",this.curr_id);
            param.append("content",file);
            param.append("to_type",this.to_type);
            param.append("msg_type",1);

            let loading = this.$toast.loading();
            this.$axios.post(this.$api_url.kf_send,param).then((res)=>{
                if(res.data.code === 0){
                    this.$toast.success(res.data.msg);
                    this.his.push(res.data.data);

                } else{
                    this.$toast.fail(res.data.msg);
                }
            }).catch((err)=>{
                this.$toast.fail(err.message);
            }).then(()=>{
                this.loading = false;
                loading.hide();
            })
        },
        getData(){
            let loading = this.$toast.loading();
            this.$axios.get(this.$api_url.user).then((res)=>{
                this.user = res.data;
                this.initServer()
            }).catch((err)=>{
                this.$toast.fail(err.message)
            }).then(()=>{
                loading.hide();
            })
        },
        getMsgList(){
            let loading = this.$toast.loading();
            this.$axios.get(this.$api_url.kf_get_list+"?uid="+this.curr_id+"&type=daichong").then((res)=>{
                this.his = res.data;
            }).catch((err)=>{
                this.$toast.fail(err.message)
            }).then(()=>{
                loading.hide();
            })
        },
        getMsg(id){
            let loading = this.$toast.loading();
            this.$axios.get(this.$api_url.kf_get_msg+"?id="+id).then((res)=>{
                if(res.data){
                    this.his.push(res.data);

                }
            }).catch((err)=>{
                this.$toast.fail(err.message)
            }).then(()=>{
                loading.hide();
            })
        },
        playAutio () {
            let audio = document.getElementById('audio-tips')
            if (audio) {
                audio.play()
            }
        },
        copyHere(elem){
            let clipboard = new this.$clipboard('#'+elem);
            clipboard.on('success', ()=> {
                this.$toast.success(this.$t('KfePage.fzcg')+this.$t('KfePage.zzdkwx')+"!");
                setTimeout(()=>{
                    try{
                        let args = {
                            type:'open_wechat',
                            data:''
                        };
                        Ak.postMessage(JSON.stringify(args));
                    } catch (e) {
                        location.href="weixin://";
                    }
                },3000);
            });
            clipboard.on('error', ()=> {
                this.$toast.fail(this.$t('KfePage.fzsb'));
            });
        },
        onSend(){
            if(this.text.length==0){
                return
            }
            let loading = this.$toast.loading();
            this.$axios.post(this.$api_url.kf_send,this.$qs.stringify({
                to_uid: this.curr_id,
                content: this.text,
                to_type: this.to_type,
            })).then((res)=>{
                if(res.data.code == 0){
                    this.text=""
                    this.$toast.success(res.data.msg);
                    this.his.push(res.data.data);

                } else{
                    this.$toast.fail(res.data.msg);
                }
            }).catch((err)=>{
                this.$toast.fail(err.message);
            }).then(()=>{
                loading.hide();
            })
        }
    },
    created(){
      this.curr_user = this.$route.query.nickname;
      this.curr_id = this.$route.query.id;
    },
    mounted() {
      this.getData();
      this.getMsgList();
    },
    beforeDestroy(){
        this.$socket.emit('disconnect');
    },
    socket: {
        // Prefix for event names
        // prefix: "/counter/",
        // If you set `namespace`, it will create a new socket connection to the namespace instead of `/`
        // namespace: "/counter",
        events: {
            // Similar as this.$socket.on("changed", (msg) => { ... });
            // If you set `prefix` to `/counter/`, the event name will be `/counter/changed`
            //
            changed(msg) {
                console.log("Something changed: " + msg);
            },
            connect() {
                console.log("Websocket connected to " + this.$socket.nsp);
                if(this.user.id!=undefined){
                    this.$socket.emit('login', 'user_'+this.user.id);
                }
            },

            disconnect() {
                console.log("Websocket disconnected from " + this.$socket.nsp);
            },

            error(err) {
                console.error("Websocket error!", err);
            }

        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
  .nut-tab{
    border:none;
    padding:0;
  }
</style>
<style scoped>
  table{
    border-collapse: collapse;
    width:100%;
  }
  table td{
    border:thin solid #ccc;
    padding:0.5rem;

  }
  .tab-box{
    border:none;
    padding:0;
  }
  .bottom-tips{
    height:2rem;
    line-height:2rem;
  }
  .total-box{
    height: 2rem;
    line-height: 2rem;
    font-size: 1rem;
  }

  .header{
    background: url(/static/img/profile-bg.png);
    background-size: 100% 100%;
  }

  .kf-list li{
    height: 1.4rem;
    line-height: 1.4rem;
    margin: 0.4rem;
    border: thin solid #ccc;
    border-radius: 0.2rem;
    overflow: hidden;
  }
  .kf-list li div{
    float:left;
  }
  .kf-list li div:first-child{
    width:30%;
  }
  .kf-list li div:last-child{
    width:70%;
    text-align: left;
  }
  .kf-list img{
    width:1rem;
  }
  .tips-text{
    padding: 0.3rem;
    font-size: 0.4rem;
    line-height: 0.7rem;
    text-align: left;
    background: #ffa500b5;
    color: #fff;
    width: 90%;
    margin: 0.3rem auto;
    border-radius: 0.3rem;
    border-style: double;
  }

  .his-list{
    padding-bottom:1rem;
    overflow-y: scroll;
  }
  .his-list li .msg-row{
    overflow: hidden;
    text-align: left;
    padding: 0.1rem 0.3rem;
    margin: 0.2rem;
    display: flex;
    flex-wrap: nowrap;
  }
  .his-list li .msg-row div{
    position: relative;
  }
  .his-list li .msg-row.no_self div:first-child{
    flex: 1;
  }
  .his-list li .msg-row.no_self div:last-child{
    padding-left: 0.3rem;
    border:thin solid #ccc;
    border-radius: 0.1rem;
    background: #fff;
    flex: 4;
    margin-left: 10px;
  }
  .his-list li .msg-row.self div:last-child{
    flex: 1;
    padding-left: 0.3rem;
  }
  .his-list li .msg-row.self div:first-child{
    border:thin solid #ccc;
    border-radius: 0.1rem;
    background: #fff;
    flex: 4;
    padding-left:10px;
  }
  .his-list li .msg-row.no_self div:first-child img{
    width:100%;
    border-radius: 50%;
    border:thin solid #ccc;
    padding:0.1rem;
    background: #fff;
  }
  .his-list li .msg-row.self div:last-child img{
    width:100%;
    border-radius: 50%;
    border:thin solid #ccc;
    padding:0.1rem;
    background: #fff;
  }
  .time_at{
    position: absolute;
    bottom: 0;
    right: 0.1rem;
    color: #777;
  }
  .tools-img{
    width:20px;
    height:20px;
  }
</style>
